from flask import render_template, g, redirect, request, jsonify, current_app, session
from info.utils.common import user_getter
from info import db, constants
from info.models import Category, News
from info.utils.response_code import RET
from . import user_blue
from info.utils.image_storage import storage


@user_blue.route('/news_list')
@user_getter
def news_list():
    # 获取参数
    user = g.user
    try:
        page = int(request.args.get("page", 1))
    except Exception as e:
        current_app.logger(e)
        page = 1
    news_models, news_list, current_page, total_page = [], [], 1, 1
    paginate = News.query.filter(News.user_id == user.id).order_by(News.create_time.desc()).paginate(page,
                                                                                                     constants.USER_COLLECTION_MAX_NEWS,
                                                                                                     False)
    current_page = paginate.page
    total_page = paginate.pages
    for new_item in paginate.items:
        news_list.append(new_item.to_review_dict())

    data = {
        "news_list": news_list,
        "total_page": total_page,
        "current_page": current_page
    }
    return render_template("news/user_news_list.html", data=data)


@user_blue.route('/news_release', methods=["GET", "POST"])
@user_getter
def news_release():
    # 1. 用户可以在个人中心发布新闻
    # 2. 发布完毕新闻需要通过审核才能显示
    # 3. 用户发布完毕新闻跳转到用户新闻列表
    # 4. 后台管理员对新闻进行审核
    # 5. 如果某条新闻是用户发布的.那么在新闻详情页展示用户的个人资料
    # 6. 需要更新新闻查询条件,添加status==0
    if request.method == "GET":
        # 获取包含分类的列表,并渲染模板
        category_models, category_list = [], []
        try:
            category_models = Category.query.all()
        except Exception as e:
            current_app.logger(e)
        # 模型转列表
        for category in category_models:
            category_list.append(category.to_dict())
        category_list.pop(0)

        data = {
            "category_list": category_list
        }
        return render_template("news/user_news_release.html", data=data)

    # POST请求==>> 获取数据 ==>> 上传图像 ==>> 添加数据
    # 获取参数&校验参数
    user = g.user
    source = "个人发布"  # 新闻来源

    title = request.form.get("title")  # 新闻标题
    digest = request.form.get("digest")  # 新闻摘要
    content = request.form.get("content")  # 新闻内容
    index_image = request.files.get("index_image")  # 首页图像, 注意,此处使用files.get
    category_id = request.form.get("category_id")  # 分类ID

    if not all([title, digest, content, index_image, category_id]):  # 判断数据是否齐全
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    try:  # 尝试读取图像
        image_data = index_image.read()
        category_id = int(category_id)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    try:  # 读取数据库分类名
        category_models = Category.query.get(category_id)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")
    if not category_models:  # 判断是否存在这种分类名
        return jsonify(errno=RET.NODATA, errmsg="无分类数据")

    # 逻辑处理
    try:  # 尝试将图片上传七牛云
        image_name = storage(image_data)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.THIRDERR, errmsg="图片上传失败")

    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.category_id = category_id
    news.user_id = user.id
    news.status = 1  # 1代表待审核状态
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    return jsonify(errno=RET.OK, errmsg="发布成功,等待审核")

    # 提交数据库,并设置为审核中

    # 跳转到新闻列表页


@user_blue.route('/follow')
def follow():
    return render_template("news/user_follow.html")


@user_blue.route('/collection')
@user_getter
def collection():
    # 获取页码
    page = request.args.get("page", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger(e)
        page = 1
    user = g.user
    collection_models = None
    current_page = 1
    total_page = 1
    collection_list = []
    try:
        # False 为找不到数据时不报404
        paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取分页数据
        for collection in paginate.items:
            collection_list.append(collection.to_dict())
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger(e)

    data = {
        "collection_list": collection_list,
        "current_page": current_page,
        "total_page": total_page
    }

    return render_template("news/user_collection.html", data=data)


@user_blue.route('/pass_info', methods=["GET", "POST"])
@user_getter
def pass_info():
    if request.method == "GET":
        return render_template("news/user_pass_info.html")
    user = g.user
    # 获得参数
    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')

    if not all([new_password, old_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原密码错误")

    user.password = new_password

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
    return jsonify(errno=RET.OK, errmsg="密码修改成功!")


@user_blue.route('/pic_info', methods=["GET", "POST"])
@user_getter
def pic_info():
    user = g.user
    if request.method == "GET":
        return render_template("news/user_pic_info.html", data={"user": user.to_dict()})

    # 获取参数&校验参数
    try:
        avatar_data = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 上传七牛云
    try:
        avatar_name = storage(avatar_data)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.THIRDERR, errmsg="七牛云上传失败")

    user.avatar_url = avatar_name

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    return jsonify(errno=RET.OK, errmsg="OK", data={"avatar_url": constants.QINIU_DOMIN_PREFIX + avatar_name})


@user_blue.route('/base_info', methods=["GET", "POST"])
@user_getter
def base_info():
    user = g.user
    if request.method == "GET":
        return render_template("news/user_base_info.html", data={"user": user.to_dict()})

    # 获取参数
    signature = request.json.get("signature")
    nick_name = request.json.get("nick_name")
    gender = request.json.get("gender")
    if not all([gender, nick_name]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 验证性别参数是否正确
    if gender not in ["MAN", "WOMAN"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 修改参数
    user.nick_name = nick_name
    user.gender = gender
    user.signature = signature

    # 提交数据到数据库
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    # 更新登录信息中的nick_name
    session["nick_name"] = nick_name

    return jsonify(errno=RET.OK, errmsg="更新成功")


@user_blue.route('/info')
@user_getter
def user_info():
    user = g.user
    if not user:
        return redirect("/")
    data = {
        "user": user.to_dict()
    }
    return render_template("news/user.html", data=data)
